package cn.com.header.core.util;
import com.google.common.collect.Maps;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * @author Yuanyifeng
 * @date 2017-11-24
 * @time 15:13
 */
public class MailUtil {


    /**
     * 发件人电子邮箱
     */
    private static final String  FROM = "dcampus@foxmail.com";
    /**
     * 电子邮箱授权码
     */
    private static final String PASSWORD="mkwtiykkyimnchfd";

    /**
     *  指定发送邮件的主机为 smtp.qq.com
      */
    private static final String HOST = "smtp.qq.com";

    /**
     *
     * @param userEmails 邮箱地址数组
     * @param subject 邮件主题
     * @param text 邮件文本内容
     * @param filePaths 附件路径
     * @throws Exception
     */
    public static Map<String,Object> sendMail(Set<String> userEmails, String subject, String text, String[] filePaths) throws Exception{

        Map<String,Object> infoMap= Maps.newHashMap();
        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", HOST);

        properties.put("mail.smtp.auth", "true");
        MailSSLSocketFactory sf =new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication()
            {     //qq邮箱服务器账户、第三方登录授权码
                return new PasswordAuthentication(FROM, PASSWORD); //发件人邮件用户名、密码
            }
        });

        try{
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            String nick="";
            try {
                nick=javax.mail.internet.MimeUtility.encodeText("恒峰信息");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            message.setFrom(new InternetAddress(nick+" <"+FROM+">"));
            // Set Subject: 主题文字
            message.setSubject(subject);

            // 创建消息部分
            BodyPart messageBodyPart = new MimeBodyPart();

            // 消息
            messageBodyPart.setText(text);

            // 创建多重消息
            Multipart multipart = new MimeMultipart();

            // 设置文本消息部分
            multipart.addBodyPart(messageBodyPart);

            // 附件部分

            if(filePaths!=null)//附件
            {
                File file;
                for(int i=0;i<filePaths.length;i++){
                    messageBodyPart = new MimeBodyPart();
                    //设置要发送附件的文件路径
                    file=new File(filePaths[i]);
                    FileDataSource  source = new FileDataSource(file);
                    messageBodyPart.setDataHandler(new DataHandler(source));
                    //处理附件名称中文（附带文件路径）乱码问题
                    String fileName=file.getName();
                    String newFileName=fileName;
                    if(fileName.contains("_")){
                        newFileName=fileName.substring(0,fileName.indexOf("_"))+fileName.substring(fileName.indexOf("."));
                    }
                    newFileName=MimeUtility.encodeText(newFileName);
                    newFileName = newFileName.replaceAll("\r", "").replaceAll("\n", "");
                    messageBodyPart.setFileName(newFileName);
                    multipart.addBodyPart(messageBodyPart);
                }
            }

            // 发送完整消息
            message.setContent(multipart );

            //添加接收者
            String errorStr="";
            for(String email:userEmails){
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
                try{
                    //   发送消息
                    Transport.send(message);
                }
                catch (Exception e){
                    errorStr+=email+",";
                }
            }
            //如果有发送失败的邮箱，进行记录
            if(!"".equals(errorStr)){
                errorStr=errorStr.substring(0,errorStr.length()-1);
                errorStr+="邮箱发送失败,请核查后再发送";
                infoMap.put("error",errorStr);
            }
        }catch (MessagingException mex) {
            infoMap.put("error","邮箱发送失败，请重新尝试");
            mex.printStackTrace();
        }
        return infoMap;
    }
}
